<?php

namespace app\dao\office;

use app\dao\BaseDao;
use app\model\office\OfficeStudyRecord;

class OfficeStudyRecordDao extends BaseDao
{

    public function index(array $where)
    {
        return $this ->search() ->with(['users' => function($query){
            $query -> withField(['id','name']);
        },'officeClass' => function($query){
            $query -> withField(['id','title']);
        }]) -> where('website_id',$where['website_id']) -> paginate($where['pageSize']);
    }

    public function updateDao(array $where)
    {
        return $this -> search() -> update($where);
    }

    public function deleteDao(array $where)
    {
        return $this->getModel()-> whereIn('id',$where['id']) -> update(['delete_time' => date('Y-m-d H:i:s', time())]);
    }

    public function createDao(array $where)
    {
        return $this -> getModel() -> create($where);
    }

    protected function setModel(): string
    {
        return  OfficeStudyRecord::class;
    }

    //----------------------------------------------api---------------------------------------------------------
    /*
     * 保存学习记录
     */
    public function insertVideo(array $where){
        $data = $this->getModel()
            ->where('website_id',$where['website_id'])
            ->where('class_id',$where['class_id'])
            ->where('chapter_id',$where['chapter_id'])
            ->where('user_id',$where['user_id'])
            ->find();
        if ($data){
            if ($data['is_pass']==1){
                $where['is_pass']=1;
            }
            $result = $this->getModel()
                ->where('website_id',$where['website_id'])
                ->where('class_id',$where['class_id'])
                ->where('chapter_id',$where['chapter_id'])
                ->where('user_id',$where['user_id'])
                -> update($where);
        }else{
            $result = $this->getModel() -> insert($where);
        }
        return $result;
    }
    /*
     * 查询学习记录
     */
    public function selectvideo(array $where){
        return $this->search()
            ->with(['chapter'=>function($query){
                $query->field(['id','url']);
            }])
            ->where('website_id',$where['website_id'])
            ->where('class_id',$where['class_id'])
            ->where('user_id',$where['user_id'])
            ->order('update_time','desc')
            ->field(['id','chapter_name','is_pass','play_time','chapter_id'])
            ->find();

    }
}